package login

//annotation:Login-service
//author:{"name":"Login","tel":"18928776452","email":"XUnion@GMail.com"}

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gorilla/sessions"
	"io"
	"net/http"
	"os"
	"sevlteServer/auto"
	"sevlteServer/tool"
)

var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))

func Enroll(author string) {
	var developer *tool.ModuleAuthor
	if author != "" {
		var d tool.ModuleAuthor
		err := json.Unmarshal([]byte(author), &d)
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		developer = &d
	}

	auto.AddService(&tool.ServeEndPoint{
		Fn: login,

		Path: "/login",
		Name: "login",

		Developer: developer,
	})

	auto.AddService(&tool.ServeEndPoint{
		Fn: islogin,

		Path: "/islogin",
		Name: "islogin",

		Developer: developer,
	})

	auto.AddService(&tool.ServeEndPoint{
		Fn: logout,

		Path: "/logout",
		Name: "logout",

		Developer: developer,
	})
}

func login(r *http.Request, w http.ResponseWriter) {
	//session, _ := store.Get(r, "session-name")
	//fmt.Println(session.Values["account"])
	//// Set some session values.
	//if session.Values["login"] == true {
	//	msg := replyProto{
	//		Status: 0,
	//		Msg:    "success",
	//	}
	//	reply(w, &msg)
	//	return
	//}

	body, err := io.ReadAll(r.Body)
	if err != nil {
		fmt.Println(err.Error())
		tool.Resp(w, &tool.ReplyProto{Status: -100})
		return
	}

	jsonMap := make(map[string]interface{})
	//将json字符串转换成map
	err = json.Unmarshal(body, &jsonMap)

	var passwd string
	err = tool.DbPool.QueryRow(context.Background(), "select password from chat_user where account=$1", jsonMap["account"]).Scan(&passwd)
	if err != nil {
		fmt.Println(err.Error())
		tool.Resp(w, &tool.ReplyProto{Status: -100})
		return
	}
	if passwd == jsonMap["password"] {

		session, _ := store.Get(r, "session-name")
		// Set some session values.
		session.Values["user"] = jsonMap["account"]
		session.Values["login"] = true
		// Save it before we write to the response/return from the handler.
		err = session.Save(r, w)
		if err != nil {
			fmt.Println(err.Error())
		}

		msg := tool.ReplyProto{
			Status: 0,
			Msg:    "success",
		}
		tool.Resp(w, &msg)
		return
	}
	tool.Resp(w, &tool.ReplyProto{Status: -100})
}

func islogin(r *http.Request, w http.ResponseWriter) {
	type Session struct {
		Status  int    `json:"status"`
		Account string `json:"account"`
	}

	session, _ := store.Get(r, "session-name")
	fmt.Println(session.Values["user"], session.Values["login"])
	// Set some session values.
	if session.Values["login"] != true {
		tool.Resp(w, &tool.ReplyProto{Status: -100})
		return
	}
	reply := &Session{Status: 0, Account: session.Values["user"].(string)}
	buf, err := json.Marshal(&reply)
	if err != nil {
		_, err := w.Write([]byte(fmt.Sprintf(`{"code":-300,"msg":"%s"}`, err.Error())))
		if err != nil {
			fmt.Println(err.Error())
			return
		}
		fmt.Println(err.Error())
		return
	}

	_, err = w.Write(buf)
	if err != nil {
		fmt.Println(err.Error())
	}
}

func logout(r *http.Request, w http.ResponseWriter) {

	session, _ := store.Get(r, "session-name")

	session.Values["user"] = nil
	session.Values["login"] = false

	session.Options.MaxAge = -1

	err := session.Save(r, w)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	tool.Resp(w, &tool.ReplyProto{Status: 0})
}
